import {Form, FormField, LinkButton, TextBox, ComboBox} from "rc-easyui";
import {useState} from "react";
import React from "react";
import {tfield, tparam} from "@kordar-lib/i18n";
import {fetchConfigOptions} from "@kordar/easyui-tpl";
import {fetchConfigOptionsWithList} from "../../util/helper";


const Search = ({ctx, pageConfig, fetchConfig}) => {

    let initData = {name: "", driver: ""}
    const [searchData, setSearchData] = useState(initData)

    const submit = () => {
        let conditions = [
            {key: "name", value: searchData.name, type: "LIKE", filter_empty: true},
            {key: "driver", value: searchData.driver, type: "EQ", filter_empty: true}
        ]
        let searchBody = {conditions: conditions}
        ctx?.search(searchBody)
    }

    const reset = () => {
        setSearchData(initData)
        ctx?.reset()
        forceRefresh()
    }

    const handleChange = (name, value) => {
        setSearchData({
            ...searchData,
            [name]: value,
        });
    };

    const [refreshKey, setRefreshKey] = useState(0);

    const forceRefresh = () => {
        setRefreshKey(prevKey => prevKey + 1);
    };

    return (
        <Form
            className="admin-search-panel"
            labelWidth={"auto"}
            model={searchData}
            key={refreshKey}
            onChange={handleChange}
            labelPosition="before"
        >
            <FormField name="name" label={tfield(pageConfig, "name.label", "Name")}>
                <TextBox value={searchData.name}></TextBox>
            </FormField>
            <FormField name="driver" label={tfield(pageConfig, "driver.label", "Driver")}>
                <ComboBox data={fetchConfigOptionsWithList(fetchConfig, "driver", pageConfig)} value={searchData.driver} />
            </FormField>
            <FormField>
                <LinkButton iconCls="iconfont icon-search color-deep-sky-blue" onClick={submit}
                            style={{marginRight: '5px'}}>
                    {tparam(pageConfig, 'search.text', 'Search')}
                </LinkButton>
                <LinkButton iconCls="iconfont icon-refresh2 color-deep-sky-blue" onClick={reset}>
                    {tparam(pageConfig, 'reset.text', 'Reset')}
                </LinkButton>
            </FormField>
        </Form>
    )
}

export default Search
